from flask import Flask, render_template, request, jsonify, session
import json
import random
from datetime import datetime
import os

app = Flask(__name__)
app.secret_key = 'your_secret_key_here'

# 加载数据
with open('data/medical_knowledge.json', 'r', encoding='utf-8') as f:
    medical_knowledge = json.load(f)

with open('data/cases.json', 'r', encoding='utf-8') as f:
    cases = json.load(f)

with open('data/questions.json', 'r', encoding='utf-8') as f:
    questions = json.load(f)


# 初始化用户会话数据
def init_user_data():
    if 'user_data' not in session:
        session['user_data'] = {
            'level': 'beginner',
            'goals': [],
            'progress': {},
            'weak_areas': [],
            'test_history': []
        }


# 智能问答系统
def answer_medical_question(question):
    # 这里可以集成更复杂的NLP模型，这里简化实现
    question_lower = question.lower()
    for topic in medical_knowledge:
        if topic['topic'].lower() in question_lower:
            return {
                'answer': topic['description'],
                'explanation': topic['explanation'],
                'related_topics': topic['related']
            }
    return {
        'answer': "我暂时无法回答这个问题，但这里有一些相关的医学知识可能对您有帮助。",
        'explanation': "",
        'related_topics': [t['topic'] for t in medical_knowledge[:3]]
    }


# 生成个性化学习路径
def generate_learning_path(level, goals):
    path = []
    if level == 'beginner':
        path.append("基础医学知识")
        path.append("解剖学基础")
        path.append("生理学基础")
    elif level == 'intermediate':
        path.append("病理学")
        path.append("药理学")
        path.append("诊断学基础")
    else:
        path.append("临床医学高级课程")
        path.append("专科医学知识")

    for goal in goals:
        if goal == 'usmle':
            path.extend(["USMLE Step 1 准备", "临床案例解析"])
        elif goal == 'clinical':
            path.extend(["临床技能训练", "病例分析"])

    return path


# 获取推荐知识点
# 获取推荐知识点
def get_recommendations():
    weak_areas = session['user_data']['weak_areas']
    if not weak_areas:
        # 确保 medical_knowledge 中有足够多的主题
        available_topics = [t['topic'] for t in medical_knowledge]
        sample_size = min(3, len(available_topics))  # 取较小的值
        return random.sample(available_topics, sample_size) if available_topics else ["基础医学知识"]
    return weak_areas
















# 获取虚拟病例
def get_case(case_id=None):
    if case_id:
        for case in cases:
            if case['id'] == case_id:
                return case
        return cases[0]
    return random.choice(cases)


# 评估答案
def evaluate_answer(question_id, user_answer):
    for q in questions:
        if q['id'] == question_id:
            correct = q['answer'].lower() == user_answer.lower()
            explanation = q['explanation'] if correct else f"正确答案是: {q['answer']}. {q['explanation']}"

            # 更新用户数据
            if not correct:
                session['user_data']['weak_areas'].append(q['topic'])
                session.modified = True

            return {
                'correct': correct,
                'explanation': explanation,
                'topic': q['topic']
            }
    return {'correct': False, 'explanation': "问题不存在", 'topic': ''}


# 生成模拟考试
def generate_mock_exam(num_questions=10):
    exam_questions = random.sample(questions, min(num_questions, len(questions)))
    return exam_questions


# 路由
@app.route('/')
def index():
    init_user_data()
    return render_template('index.html')


@app.route('/chat', methods=['GET', 'POST'])
def chat():
    init_user_data()
    if request.method == 'POST':
        question = request.form.get('question')
        response = answer_medical_question(question)
        return jsonify(response)
    return render_template('chat.html')


@app.route('/learning_path')
def learning_path():
    init_user_data()
    user_data = session['user_data']
    path = generate_learning_path(user_data['level'], user_data['goals'])
    return render_template('learning_path.html', path=path)


@app.route('/cases')
def case_studies():
    init_user_data()
    case = get_case()
    return render_template('cases.html', case=case)


@app.route('/cases/<case_id>')
def specific_case(case_id):
    init_user_data()
    case = get_case(case_id)
    return render_template('cases.html', case=case)


@app.route('/assessment', methods=['GET', 'POST'])
def assessment():
    init_user_data()
    if request.method == 'POST':
        data = request.get_json()
        result = evaluate_answer(data['question_id'], data['answer'])
        return jsonify(result)

    # GET请求返回评估页面
    question = random.choice(questions)
    return render_template('assessment.html', question=question)


@app.route('/mock_exam')
def mock_exam():
    init_user_data()
    exam_questions = generate_mock_exam(5)  # 简化示例，实际可以使用更多题目
    return render_template('mock_exam.html', questions=exam_questions)


@app.route('/progress')
def progress():
    init_user_data()
    user_data = session['user_data']
    return render_template('progress.html', user_data=user_data)


@app.route('/resources')
def resources():
    init_user_data()
    recommendations = get_recommendations()
    return render_template('resources.html', recommendations=recommendations)


@app.route('/update_profile', methods=['POST'])
def update_profile():
    init_user_data()
    level = request.form.get('level')
    goals = request.form.getlist('goals')

    session['user_data']['level'] = level
    session['user_data']['goals'] = goals
    session.modified = True

    return jsonify({'status': 'success'})


if __name__ == '__main__':
    app.run(debug=True)


















